
"""
{"access_token":"c91787b4-16ae-4955-8e6b-cd0a6f818ea7","token_type":"bearer","refresh_token":"0063062f-fe40-4ac2-8557-b2a77d25daf3","expires_in":1295999}

账号或密码不正确

[]

()

"""
import json

import allure
from jsonpath import jsonpath
from unittest import TestCase
from tools.handle_logs import mylog
class HandleResponse:
    def __init__(self):
        #实例化测试用例类，要使用他自带的断言方法
        self.my_assert = TestCase()
    #统一将接口响应结果二次封装成json数据
    def handle_response(self,response):
        try:
            if isinstance(response.json(),dict):
                mylog.info(msg=f"响应结果是json格式，response.json: {response.json()}")
                return {"resp_type":"json","response":response.json()}
        except Exception as e:

                return {"resp_type":"str","response":response.text}


    #断言响应结果
    @allure.step("断言响应结果")
    def assert_response(self,response,expected_data):
        try:
            if expected_data:
                #测试结果
                actual_data = {}
                expected_data = expected_data if isinstance(expected_data,dict) else json.loads(expected_data)
                #根据期望结果字典的key，创建测试结果字典
                for key in expected_data:
                    actual_data[key] = jsonpath(response,f"$..{key}")[0]
                #断言
                self.my_assert.assertEqual(expected_data,actual_data)
                print("接口断言成功")
            else:
                print("expected_data字段为空，无需做接口断言")
        except Exception as e:
            raise AssertionError(f"断言失败{e}")



